package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Album;
import cn.edu.seu.herald.informationplatform.dao.database.AlbumDao;

public class AlbumRequired implements Filter {
	
	public static final String PARAM_NAME_OF_ALBUM_ID = "album";

	public static final String ALBUM_BEAN_NAME = "albumBean";
	
	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		boolean success = doSpecified(httpRequest, httpResponse);
		if (!success) {
			httpResponse.sendError(404);
			return;
		}
		
		try {
			String albumIdParam = request.getParameter(
					PARAM_NAME_OF_ALBUM_ID);
			AlbumDao access = AlbumDao.getDao();
			Album album = access.getAlbumById(Integer.valueOf(albumIdParam));
			httpRequest.setAttribute(ALBUM_BEAN_NAME, album);
		} catch (NumberFormatException e) {
			httpResponse.sendError(400);
			return;
		} catch (SQLException e) {
			httpResponse.sendError(500);
			return;
		}

		chain.doFilter(request, response);
	}
	
	private boolean doSpecified(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse) {
		try {
			// 获取请求中的活动标识
			String albumIdParam = httpRequest.getParameter(
					PARAM_NAME_OF_ALBUM_ID);
			String leagueIdParam = httpRequest.getParameter(
					LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
			int leagueId = Integer.valueOf(leagueIdParam);
			if (albumIdParam == null) {
				return false;
			}
			AlbumDao albumAccess = AlbumDao.getDao();
			int albumId = Integer.valueOf(albumIdParam);
			if (!albumAccess.hasId(albumId)) {
				return false;
			}
			Album album = albumAccess.getAlbumById(albumId);
			if (album.getLeagueId() != leagueId) {
				return false;
			}
		} catch (SQLException e) {
			return false;
		} catch (NumberFormatException e) {
			return false;
		}

		return true;
	}

}
